package cn.hdu.liang.dao;

import cn.hdu.liang.po.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.sql.SQLException;
import java.util.List;

public class UserDaoImpl implements UserDao {

    private SqlSessionFactory sqlSessionFactory;

    public UserDaoImpl(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }

    @Override
    public User findUserById(int id) throws SQLException {
        SqlSession session = sqlSessionFactory.openSession();
        User user = session.selectOne("test.findUserById", id);
        session.close();
        return user;
    }

    @Override
    public List<User> findUserByName(String name) throws SQLException {
        SqlSession session = sqlSessionFactory.openSession();
        List<User> users = session.selectList("test.findUserByName", name);
        session.close();
        return users;
    }

    @Override
    public void insertUser(User user) throws SQLException {
        SqlSession session = sqlSessionFactory.openSession();
        session.insert("test.insertUser", user);
        session.commit();
        session.close();
    }

    @Override
    public void deleteUser(int id) throws SQLException {
        SqlSession session = sqlSessionFactory.openSession();
        session.delete("test.deleteUser", id);
        session.commit();
    }
}
